from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import my_spider
import time
from datetime import datetime


class S(BaseHTTPRequestHandler):
    # def __init__(self):
        # super(S, self).__init__(request, client_address, server):
        # print('init')
    s = my_spider.Spider(headless=True)
    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):
        paths = {
            '/foo': {'status': 200},
            '/bar': {'status': 302},
            '/baz': {'status': 404},
            '/qux': {'status': 500}
        }
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        if self.path in paths:
            self.respond(paths[self.path])
        else:
            self.respond({'status': 500})
        # self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])  # <--- Gets the size of data
        post_data = self.rfile.read(content_length)  # <--- Gets the data itself

        logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n",
                     str(self.path), str(self.headers), post_data.decode('utf-8'))

        res = "You Input: " + post_data.decode('utf-8')

        self.do_HEAD()
        # self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
        self.wfile.write("{}".format(res).encode('utf-8'))
        # self.wfile.write("POST request for {ASS}".format(data).encode('utf-8'))

    def respond(self, opts):
        response = self.handle_http(opts['status'], self.path)
        self.wfile.write(response)

    def handle_http(self, status_code, path):
        print("本次接受get请求时间为%s"%(datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")))
        self.send_response(status_code)
        self.send_header('Content-type', 'application/json;charset=UTF-8')
        self.end_headers()
        lt_t = time.time()
        content = "未收到账号信息，请检查"
        # s = my_spider.Spider(headless=True)
        print('本次处理用时%fs' % (time.time() - lt_t))
        if 'Account' in self.headers:
            flag = self.s.check_login(self.headers['Account'], self.headers['Password'])
            # flag = True
            print('本次处理用时%fs' % (time.time() - lt_t))
            if flag is not False:
                print(self.headers)
                print(type(self.headers))
                content = 'error'
                if self.headers['goal'] == 'grade':
                    print(self.headers['Account'])
                    print(self.headers['Password'])
                    # print(type(self.headers['Password']))
                    cookies = self.s.read_cookie(self.headers['Account'], self.headers['Password'])
                    content = self.s.get_grades(self.headers['Account'], cookies, int(self.headers['xnm']), int(self.headers['xqm']))
                elif self.headers['goal'] == 'user_information':
                    cookies = self.s.read_cookie(self.headers['Account'], self.headers['Password'])
                    content = self.s.get_user_infomation(self.headers['Account'], cookies)
                elif self.headers['goal'] == 'student_status':
                    cookies = self.s.read_cookie(self.headers['Account'], self.headers['Password'])
                    content = self.s.get_user_student_status(self.headers['Account'], cookies)
                elif self.headers['goal'] == 'CET_status':
                    cookies = self.s.read_cookie(self.headers['Account'], self.headers['Password'])
                    content = self.s.get_cet_grade(self.headers['Account'], cookies)
            else:
                content = "账号或密码错误，请检查"

        print(content)
        # content = content
        print('本次处理用时%fs' % (time.time() - lt_t))
        return bytes(content, 'UTF-8')


def run(server_class=HTTPServer, handler_class=S, port=8080):
    print("run()")
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print("httpd.server_close()")
    logging.info('Stopping httpd...\n')


if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()
